package enemies
{
	import org.flixel.*;
	
	import treasures.*;
	
	/**
	 * ...
	 * @author JAC
	 */
	public class Robber extends Enemy
	{
		public static const COLLECTING:uint = 0;
		public static const ESCAPING:uint = 1;
		public static const AVOIDING:uint = 2;
		public static const LEAVING:uint = 3;
		
		public function Robber(i:uint = 0, j:uint = 0)
		{
			super(i, j);
			
			loadGraphic(Assets.ImgEnemyRobber, true);
			
			addAnimation("UP", [0, 1, 2, 1], 6);
			addAnimation("DOWN", [3, 4, 5, 4], 6);
			addAnimation("LEFT", [6, 7, 8, 7], 6);
			addAnimation("RIGHT", [9, 10, 11, 10], 6);
			addAnimation("DYING", [12, 13, 14, 15, 16, 17, 18], 6, false);
			play("DOWN");
			
			addText("DYING", "NO!!!", 80, 2);
			addText("Sees ghost", "!!!!!", 30, 1.5);
			
			_speed = 125;
			
			state = COLLECTING;
			
			toggleLight();
		}
		
		override public function update():void
		{
			super.update();
			
			if (alive)
			{
				if (state == COLLECTING)
				{
					if (isIdle && thereAreMoreTreasures)
					{
						if (!goToNearestTreasure())
						{
							state = ESCAPING;
							return;
						}
					}
					
					if (_target != null && !_target.alive)
					{
						stopFollowingPath(true);
						pathSpeed = 0;
					}
					if (!thereAreMoreTreasures)
					{
						state = ESCAPING;
						return;
					}
					
					if (canSeePlayer(3, true))
					{
						state = AVOIDING;
						say("Sees ghost");
						if (!goToRandomTile(true))
						{
							if (!goToNearestExit(true))
							{
								stopMoving();
							}
						}
					}
				}
				else if (state == ESCAPING)
				{
					if (atExit)
					{
						state = LEAVING;
						return;
					}
					
					if (isIdle && !atExit)
					{
						goToNearestExit(false);
					}
					
					if (notMoving)
					{
						goToNearestExit(false);
					}
					
					if (canSeePlayer(3, true))
					{
						state = AVOIDING;
						say("Sees ghost");
						if (!goToRandomTile(true))
						{
							if (!goToNearestExit(true))
							{
								stopMoving();
							}
						}
					}
				}
				else if (state == AVOIDING)
				{
					if (isIdle)
					{
						if (thereAreMoreTreasures)
						{
							state = COLLECTING;
						}
						else
						{
							state = ESCAPING;
						}
					}
					
					if (isIdle && atExit && thereAreMoreTreasures && canSeePlayer(3, false) && !goToNearestTreasure(true))
					{
						goToNearestExit(true);
						state = LEAVING;
					}
				}
				else if (state == LEAVING)
				{
					if (atExit)
					{
						stopMoving();
						moveTowardsFacing();
					}
				}
			}
		}
		
		override public function kill():void
		{
			alive = false;
			stopMoving();
			say("DYING");
			play("DYING");
			FlxG.play(Assets.SndNo, Registry.soundVolume);
		}
		
		override public function overlapWithPlayer(p:Player):void
		{
			kill();
		}
	}
}